<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <link rel="stylesheet" type="text/css" href="__ROOT__ /AI_radar/css/font_Icon/iconfont.css">
    <link rel="stylesheet" type="text/css" href="__ROOT__ /AI_radar/css/message/chat.css">
    <script type="text/javascript" src="__ROOT__ /AI_radar/js/token.js"></script>
    <style>
          .file-input {
            display: inline-block;
            box-sizing: border-box;
            width: 4rem;
            height: 4rem;
            opacity: 0;
            cursor: pointer;
          }
          .select-button {
              /*color: #fff;*/
              width: 4rem;
              height: 4rem;
              position: absolute;
              text-align: center;
              border: 1px solid #ccc;
              border-radius: 3px;
              background: #fff;
          }
          #chat-tuxiang{
            /*width: 16px;*/
          }
          #select-button{
            margin:0;
            padding: 0;
          }
          #select-button>i{
            margin-top: 12px;
          }
          .jiaz{
            width: 100%;
            line-height: 35px;
            text-align: center;
            font-size: 13px;
            display: none;
          }
          .chuantu{
            width: 100%;
            height: 8rem;
            margin-top: 1px solid #ccc;
            background: #fff;
            display: none;
          }
          .chuantus{
            display: flex;
          }
        .chuantuku{
            width: 4rem;
            height: 4rem;
            margin:10px;
            /*display: inline-block*/
        }
        .chuantuPhone{
            width: 4rem;
            height: 4rem;
            margin:10px;
            line-height: 4rem;
            text-align: center;
            font-size: 13px;
            border:1px solid #ccc;
            border-radius: 5px;
            /*display: inline-block*/
        }
        /*.fasong{
            display: none;
        }*/
        .chatBox-trick{
            background: #eee;
            overflow-y: auto;
        }
        .trickFont{
            line-height: 25px;
            font-size: 13px;
            padding: 0 4px;
            margin: 5px;
            border-radius:15px;
            border:1px solid #ccc;
            display: inline-block;
            background: #fff;
        }

        .trickZ{
            width:50%;
            height: 50%;
            position: fixed;
            bottom: 92px;
            right:0;
            display: none;
        }
        .trickTop{
            width: 100%;
            height: calc(100% - 20px);
            background:#ddd;
            overflow-y:auto;
        }
        .trickBot{
            width: 0;
            height: 0;
            margin-left: 80%;
            border-top: 10px solid #ddd;
            border-left: 15px solid rgba(0,0,0,0);
            border-right: 10px solid rgba(0,0,0,0);
            border-bottom: 5px solid rgba(0,0,0,0);
        }
        .trickOne{
            width: calc(100% - 10px);
            padding:0 5px;
        }
        .trickOneTitle{
            width: 100%;
            line-height: 2rem;
            font-size: 0.9rem;
        }
        .trickOneContent{
            display: none;
        }
        .shoppingName{
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .shoppingPrice{
            color:red;
        }
        .chat-message{
            position: relative;
            display: flex;
        }
        .rights{
            width:100%;
            height: 100%;
            position: absolute;
            top: 0;
            margin: 0;
            background: rgba(0,0,0,0.5);
            z-index: 999;
            text-align: center;
            vertical-align: middle;
        }
        .rights1{
            height: 50%;
            width:100%;
        }
        .rights1s{

        }
        .phoneRequest{
            width:100%;
            line-height: 30px;
            text-align: center;
            color: #666666;
            font-size: 15px;
        }


        .chat-ji,.chat-ti{
            /*color: red;*/
            font-size: 10px;
            display: inline-block;
        }
        .div-button{
            position: fixed;
            bottom: 0.5rem;
            right: 8px;
        }
        .div-textarea{
            position: fixed;
            bottom: 0.5rem;
            left: 6px;
        }

    </style>

</head>
<body>
{include file="public/wx_share" /}
<div class="chatContainer">
    <div class="chatBtn">
        <i class="iconfont icon-xiaoxi1"></i>
    </div>
    <div class="chat-message-num">10</div>
    <div class="chatBox" ref="chatBox">
        <div class="chatBox-info">
            <div class="chatBox-kuang" ref="chatBoxkuang">
                <div class="chatBox-content" style="overflow:hidden;">
                    <div class="chatBox-content-demo" id="chatBox-content-demo" style="overflow-y: auto;">
                        <div class="jiaz">点击查看更多信息</div>
                        <div class="chatBox-content-demojia"></div>
                        <!--  -->

                    </div>
                </div>
                <div class="chatBox-trick" style="height: 42px;padding-top: 3px">
                    <div class="chatBox-tricks">
                    </div>
                </div>
                <div class="chatBox-send" style="height: 45px">
                    <div class="div-textarea" contenteditable="true"></div>
                    <div class="div-button">
                        <button id="chat-tuxiang" class="btn-default-styles spans"><i class="iconfont icon-tuxiang"></i></button>
                        <!-- <button id="chat-biaoqing" class="btn-default-styles">
                            <i class="iconfont icon-biaoqing"></i>
                        </button> -->
                        <!-- <button id="chat-tuxiang" class="btn-default-styles spans">
                            <i class="iconfont icon-tuxiang"></i>
                        </button> -->
                        <!-- <label id="chat-tuxiang" class="btn-default-styles">
                            <i class="iconfont icon-tuxiang"></i>
                        </label> -->
                        <button id="chat-fasong" class="btn-default-styles fasong" style="line-height: 31px">发送</button>
                        <!-- <button id="chat-fasong" class="btn-default-styles spans"><i class="iconfont icon-tuxiang"></i></button> -->

                        
                    </div>
                    
                    <div class="biaoqing-photo">
                        <ul>
                            <li><span class="emoji-picker-image" style="background-position: -9px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -154px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -154px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -154px;"></span>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="chuantu">
                    <div class="chuantus">
                        <div class="chuantuku">
                            <div class="mainContainer">
                                <form method="post" enctype="multipart/form-data" id="form" action="upload">
                                  <div id="box2">
                                    <button class="select-button" id="select-button" sid=''>选择图片</button>
                                    <input class="file-input select2" type="file" id="inputImage" sid='' class="hidden" multiple="multiple"/>
                                  </div>
                                </form>
                            </div>
                                    
                        </div>
                        <div class="chuantuPhone">交换手机</div>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="trickZ">
    <div class="trickTop"></div>
    <div class="trickBot"></div>
</div>
<div class="CRM_log" style="display:block;position: fixed;top: 0;left: 0;background:rgba(0,0,0,0);width:100%;height: 100%;">
    <div style="width:100%;height:100%;display:flex;vertical-align: middle;">
      <div style="width:3rem;height:3rem;margin: auto;">
        <img src="http://resource.17jxyx.com/goods/15537572830000.gif" alt="" class="load1Img" style="width:100%;height:auto;border-radius: 0.4rem;background: rgba(255,255,255,0.3)" />
       <!--  <div class="loadFont" style='width:100%;text-align: center;display: block;color:#fff;font-size: 20px;'>正在加载...</div> -->
      </div>
    </div>
</div>


<script src='__ROOT__ /AI_radar/js/jquery.js'></script>
<script type="text/javascript" src='__ROOT__ /AI_radar/js/qiniu/qiniu.min.js'></script>
<script>
    // isArraylike
    //1：聊天  3.图片  4.商品  5.交换手机号
    var userId = "{$user_id}"
    var tokensNew = "{$token}"
    console.log(tokensNew,userId)
    var pages = 1;
    var speak;
    var imgLeftHead;
    var imgRightHead;
    var userss = {$user};
    var worker = {$worker};
    console.log(userss,worker)
    document.title = userss.nickname
    // var sssss = '{"type":"login","client_name":"kk","token":"123456"}'
    // console.log(sssss)
    // console.log(JSON.parse(sssss))

    var userssImg;
    var webSend = []
    localStorage.setItem('judge',"false");//记录进入聊天页面，返回上页时不再请求数据库的消息列表

    if(userss.avatar_url){
        userssImg = userss.avatar_url;
    }else{
        userssImg = "__ROOT__ /AI_radar/image/my/tx.png"
    }
    var workerImg;
    if(worker.head_img){
        workerImg = worker.head_img
    }else{
        workerImg = "__ROOT__ /AI_radar/image/my/tx.png"
    }
    var token = window.tokens.token_boss
    var lockReconnect = false;//避免重复连接
    var wsUrl = "wss://minitest.17jxyx.com/wss";
    var ws;
    var tt;
    // 话术请求
    trickClassAjax()
    function trickClassAjax(){
        $.ajax({
            url:window.urls.url + "/my/trick/category",
            type:"POST",
            contentType: "application/json",
            dataType:"json",
            data:JSON.stringify({
                token:window.tokens.token_boss
            }),
            success:function(res){
                console.log(res.data)
                var widthNum = 2;
                var nums;
                if(res.data){
                    res.data.forEach(function(el,index){
                    console.log(el.name.length)

                        widthNum = widthNum + el.name.length * 14 + 20
                        var div
                        if(index == 0){
                            nums = el.id
                            div = "<text class='trickFont' did='"+el.id+"'>"+el.name+"</text>"
                        }else{
                            div = "<text class='trickFont' did='"+el.id+"'>"+el.name+"</text>"
                        }
                        $(div).appendTo(".chatBox-tricks");
                    })
                    // console.log(widthNum)
                     widthNum = widthNum + 3 * 14 + 20
                    // console.log(widthNum)

                }
                    var divs = "<text class='trickFont' did='0' style='width:44px;text-align: center;'>自定义</text>"
                    $(divs).appendTo(".chatBox-tricks");
                    var trickFont = document.querySelectorAll(".trickFont")
                    chatTrick(trickFont)
                $(".chatBox-tricks").css("width",widthNum+'px')
              
               
            },
            error:function(res){
              console.log(res)
              alert("请求数据失败")
            }
        })
    }
    $(".trickZ").click(function(){
        $(".trickZ").css("display","none")
    })
    //聊天记录状态改变
    messageAjax(userId)
    function messageAjax(userIds){
        $.ajax({
            url:window.urls.url + "/message/status",
            type:"POST",
            contentType: "application/json",
            dataType:"json",
            data:JSON.stringify({
                token:window.tokens.token_boss,
                uid:userIds
            }),
            success:function(res){
                console.log(res.data)
            },
            error:function(res){
              console.log(res)
              alert("请求数据失败")
            }
        })
    }
    //点击话术
    function chatTrick(arr){
        Array.from(arr).forEach(function(dom,ind){
            dom.onclick = function(){
                $(".chatBox-content").css("margin-top","0")
                $(".div-textarea").css("bottom","0.5rem")
                $(".div-button").css("bottom","0.5rem")
                $(".chuantu").css("display","none")
                chuabpan = true;
                $(".trickZ").css("display","block")
                console.log(dom.getAttribute("did"))
                if( $(".trickOne").length>1){
                    $(".trickOne").each(function(ind,el){
                        el.remove()
                    })
                }
                if(dom.getAttribute("did") == 0){
                    trickMyAjax()
                }else{
                    trickAllAjax(dom.getAttribute("did"))
                }
            }
        })
        // chatTrick(arr)
    }
    //查看话术
    function trickAllAjax(num){
        console.log(num)
        $.ajax({
            url:window.urls.url + "/my/trick/category/list",
            type:"POST",
            contentType: "application/json",
            dataType:"json",
            data:JSON.stringify({
                token:window.tokens.token_boss,
                categoryId:num
            }),
            success:function(res){
                console.log(res.data)
                if(res.data){
                    res.data.forEach(function(el,ind){
                        var div = "<div class='trickOne'><div class='trickOneTitle'>"+el.keyword+"</div><div class='trickOneContent' >"+el.content+"</div></div>"
                        $(div).appendTo(".trickTop")
                    })
                }
                var trickOne = document.querySelectorAll(".trickOne")
                trickYes(trickOne)
                
            },
            error:function(res){
              console.log(res)
              alert("请求数据失败")
            }
        })
    }
    //查看自定义话术
    function trickMyAjax(){
        $.ajax({
            url:window.urls.url + "/my/trick/list",
            type:"POST",
            contentType: "application/json",
            dataType:"json",
            data:JSON.stringify({
                token:window.tokens.token_boss,
            }),
            success:function(res){
                console.log(res.data)
                if(res.data){
                    res.data.forEach(function(el,ind){
                        var div = "<div class='trickOne'><div class='trickOneTitle'>"+el.keyword+"</div><div class='trickOneContent' >"+el.content+"</div></div>"
                        $(div).appendTo(".trickTop")
                    })
                }
                var trickOne = document.querySelectorAll(".trickOne")
                trickYes(trickOne)
            },
            error:function(res){
              console.log(res)
              alert("请求数据失败")
            }
        })
    }
    //话术确认
    function trickYes(arr){
        Array.from(arr).forEach(function(dom,ind){
            dom.onclick = function(){
                console.log(dom.childNodes[1].innerHTML)
                $(".div-textarea").html(dom.childNodes[1].innerHTML)
                $(".trickZ").css("display","none")
            }
        })
    }
    //聊天记录请求
    chatAjax(userId,pages,userssImg)
    function chatAjax(userId,pages,userssImg){
        console.log("12123123123")
        $.ajax({
            url:window.urls.url + "/message/list",
            type:"POST",
            contentType: "application/json",
            dataType:"json",
            data:JSON.stringify({
                token:window.tokens.token_boss,
                uid:userId,
                page:pages
            }),
            success:function(res){
                console.log(res.data)
                if(res.data != ''){

                    if(res.data.length==10){
                        $(".jiaz").css("display","block")
                   
                    }
                    if(res.data.length<10){
                        $(".jiaz").css("display","none")
                    }
                  $.each(res.data, function(index, el) {
                    console.log(el.id,userId)
                    var textContents = el.content
                    var time = el.time
                    var message_type = el.msg_type
                      if(el.id == userId){
                        if(el.msg_type == 1){
                            message_types1O(textContents,time)
                        }
                        if(el.msg_type == 2){
                            
                        }
                        if(el.msg_type == 3){
                            message_types3O(textContents,time)
                        }
                        if(el.msg_type == 4){
                            // console.log(el.content)
                            // console.log(el.content.name)
                            var nsmes = el.content.slice(6, el.content.indexOf(",id:"))
                            var ids = el.content.slice( el.content.indexOf(",id:")+4,el.content.indexOf(",price:"))
                            var prices = el.content.slice(el.content.indexOf(",price:") + 7, el.content.indexOf(",pictures:"))
                            var pictures = el.content.slice(el.content.indexOf(",pictures:") + 10)

                            $(".chatBox-content-demojia").prepend("<div class=\"clearfloat\">" +
                        "<div class=\"author-name\"><small class=\"chat-date\">"+time+"</small> </div> " +
                        "<div class=\"left\"><div class=\"chat-avatars\"><img src="+userssImg+" alt=\"头像\" /></div> <div class=\"chat-message\"><div class=\"shoppingZ\"><img clsas=\"shoppingImg\" src="+pictures+"><div class=\"shoppingName\">"+nsmes+"</div><div class=\"shoppingPrice\">￥"+prices+"</div></div></div> " +
                        " </div></div>");

                        }
                        // if(el.msg_type == 5){
                        //     message_types5()
                        // }
                      }else{
                        var colors,texts
                        if(el.is_read == 1){ //1:已读；0：未读
                            colors = "#666666"
                            texts = "已读"
                        }else{
                            colors = "#03f718"
                            texts = "送达"
                        }
                        if(el.msg_type == 1){
                            message_types1(textContents,colors,texts)
                        }
                        if(el.msg_type == 5){
                            message_types5()
                        }
                        if(el.msg_type == 2){
                            
                        }
                        if(el.msg_type == 3){
                            message_types3(textContents,colors,texts)
                        }
                        if(el.msg_type == 4){

                        }
                      }
                  })
                  console.log(document.querySelector(".chatBox-content-demojia"))
                  var domsHeights = document.querySelector(".chatBox-content-demojia").childNodes
                  Array.from(domsHeights).forEach(function(kds,fghsd){
                    // console.log(kds.childNodes[2].offsetHeight)
                    // console.log(kds.childNodes[2].scrollHeight)
                    // console.log(kds.scrollTop)
                  })

                    console.log($(".chatBox-content-demojia").height())
                    // console.log(parseInt($('.achatBox-content-demojia').get(0)))
                    // console.log(document.querySelector(".chatBox-content-demojia").offsetHeight)
                    // console.log(document.querySelector(".chatBox-content-demojia").clientHeight)

                    // console.log($("#chatBox-content-demo")[0].scrollHeight)
                    // $("#chatBox-content-demo").scrollTop(100);
                    document.querySelector("#chatBox-content-demo").scrollTop = 500
                    console.log(document.querySelector("#chatBox-content-demo").scrollTop)
                    // $(document).ready(function () {
                    //     console.log($(".chatBox-content-demojia").height())
                    //     $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight+1000);
                    // });
                    // var demojia = document.querySelector(".chatBox-content-demojia")
                    // // console.log($("#chatBox-content-demo")[0].scrollHeight)
                    // // console.log($("#chatBox-content-demo")[0].scrollHeight+1000)


                    // console.log($("#chatBox-content-demo")[0].scrollHeight)
                    // $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight+1000);
                    // console.log($("#chatBox-content-demo").scrollTop())
                    // console.log($(".chatBox-content-demojia").height())


                  $(".jiaz").click(function(){
                    pages++
                    $.ajax({
                        url:window.urls.url + "/message/list",
                        type:"POST",
                        contentType: "application/json",
                        dataType:"json",
                        data:JSON.stringify({
                            token:window.tokens.token_boss,
                            uid:userId,
                            page:pages
                        }),
                        success:function(res){
                          console.log(res.data)
                          if(res.data != ""){
                            
                              if(res.data.length==10){
                                $(".jiaz").css("display","block")
                                
                              }
                              if(res.data.length<10){
                                    $(".jiaz").css("display","none")
                                }
                              $.each(res.data, function(index, el) {
                                var textContents = el.content
                                var time = el.time
                                var message_type = el.msg_type
                                  if(el.id == userId){
                                    if(el.msg_type == 1){
                                        message_types1O(textContents,time)
                                    }
                                    if(el.msg_type == 2){
                                        
                                    }
                                    if(el.msg_type == 3){
                                        message_types3O(textContents,time)
                                    }
                                    if(el.msg_type == 4){

                                    }
                                  }else{
                                    var colors,texts
                                    if(el.is_read == 1){
                                        colors = "#666666"
                                        texts = "已读"
                                    }else{
                                        colors = "#03f718"
                                        texts = "送达"
                                    }
                                     if(el.msg_type == 1){
                                        message_types1(textContents,colors,texts)
                                    }
                                    if(el.msg_type == 2){
                                        
                                    }
                                    if(el.msg_type == 3){
                                        message_types3(textContents,colors,texts)
                                    }
                                    if(el.msg_type == 4){

                                    }
                                    if(el.msg_type == 5){
                                        message_types5()
                                    }
                                  }
                                   // $(document).ready(function () {
                                   //      $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                                   //  });
                              })
                          }
                         
                        },
                        error:function(res){
                          console.log(res)
                        }
                    });

                  })
                }
              

            },
            error:function(res){
              console.log(res)
            }
        });
    }
    //关闭话术框
    function offTrick(){
        document.body.onclick = function(){
            $(".trickZ").css("display","none")
        }
    }

    $(".div-textarea").click(function(){
        $(".chatBox-content").css("margin-top","0")
        $(".div-textarea").css("bottom","0.5rem")
        $(".div-button").css("bottom","0.5rem")
        $(".chuantu").css("display","none")
        chuabpan = true;
    })
    // }
    var title = $("b.facility");
    var title = $('.div-textarea');//the element I want to monitor

    title.bind('DOMNodeInserted', function(e) {

        console.log( $(e.target).html());
        // console.log( $(".div-textarea").text());

        console.log( $(e.target).html().length);
        if($(e.target).html().length>0){
            // $(".spans").css("display","none")
            // $(".fasong").css("display","inline-block")
            $(".chatBox-content").css("margin-top","0")
            $(".div-textarea").css("bottom","0.5rem")
            $(".div-button").css("bottom","0.5rem")
            $(".chuantu").css("display","none")

            chuabpan = true;
        }


    });

    var chuabpan = true;
    $(".spans").click(function(){
        if(chuabpan){
            $(".chatBox-content").css("margin-top","-8rem");
            $(".chuantu").css("display","inline-block")
            $(".trickZ").css("display","none")
            $(".div-textarea").css("bottom","8.5rem")
            $(".div-button").css("bottom","8.5rem")

            chuabpan = false
        }else{
            $(".chatBox-content").css("margin-top","0")
            $(".chuantu").css("display","none")
            $(".div-textarea").css("bottom","0.5rem")
            $(".div-button").css("bottom","0.5rem")

            chuabpan = true;
        }
        
    })

    function message_types5(){
        $(".chatBox-content-demojia").prepend("<div class=\"clearfloat\"><div class=\"phoneRequest\">请求交换手机已发送...</div></div>");
    }
    function message_types50(){
        $(".chatBox-content-demojia").append("<div class=\"clearfloat\"><div class=\"phoneRequest\">请求交换手机已发送...</div></div>");
    }


    function message_type1(textContent,id){
        // console.log(textContent)
        // var textContents =  textContent.replace(/[\n\r]/g,"<br/>")
        $(".chatBox-content-demojia").append("<div class=\"clearfloat\">" +
                "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
                "<div class=\"right\"><div class=\"chat-ti\" id="+id+">发送中</div> <div class=\"chat-message\"> " + textContent + " </div> " +
                "<div class=\"chat-avatars\"><img src="+workerImg+" alt=\"头像\" /></div> </div> </div>");
    }
    function message_type3(srcs,id){
         $(".chatBox-content-demojia").append("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
            "<div class=\"right\"><div class=\"chat-ti\" id="+id+">发送中</div><div class=\"chat-message\"><div class=\"rights\">正在发送...</div><img src=" + srcs + "></div> " +
            "<div class=\"chat-avatars\"><img src="+workerImg+" alt=\"头像\" /></div> </div> </div>");
    }
    function message_type1O(textContent,time){
         $(".chatBox-content-demojia").append("<div class=\"clearfloat\">" +
                    "<div class=\"author-name\"><small class=\"chat-date\">"+time+"</small> </div> " +
                    "<div class=\"left\"><div class=\"chat-avatars\"><img src="+userssImg+" alt=\"头像\" /></div> <div class=\"chat-message\"> " + textContent + " </div> " +
                    " </div> </div>");
    }
    function message_type3O(srcs,time){
         $(".chatBox-content-demojia").append("<div class=\"clearfloat\">" +
                    "<div class=\"author-name\"><small class=\"chat-date\">"+time+"</small> </div> " +
                    "<div class=\"left\"> <div class=\"chat-avatars\"><img src="+userssImg+" alt=\"头像\" /></div><div class=\"chat-message\"><img src=" + srcs + "></div> " +
                    " </div> </div>");
    }

    function message_types1(textContent,colors,texts){
        $(".chatBox-content-demojia").prepend("<div class=\"clearfloat\">" +
                "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
                "<div class=\"right\"> <div class=\"chat-ti\" style=\"color\:"+colors+"\">"+texts+"</div><div class=\"chat-message\"> " + textContent + " </div> " +
                "<div class=\"chat-avatars\"><img src="+workerImg+" alt=\"头像\" /></div> </div> </div>");
    }
    function message_types3(srcs,colors,texts){
         $(".chatBox-content-demojia").prepend("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
            "<div class=\"right\"> <div class=\"chat-ti\" style=\"color\:"+colors+"\">"+texts+"</div><div class=\"chat-message\"><img src=" + srcs + "></div> " +
            "<div class=\"chat-avatars\"><img src="+workerImg+" alt=\"头像\" /></div> </div> </div>");
    }
    function message_types1O(textContent,time){
         $(".chatBox-content-demojia").prepend("<div class=\"clearfloat\">" +
                    "<div class=\"author-name\"><small class=\"chat-date\">"+time+"</small> </div> " +
                    "<div class=\"left\"><div class=\"chat-avatars\"><img src="+userssImg+" alt=\"头像\" /></div> <div class=\"chat-message\"> " + textContent + " </div> " +
                    " </div> </div>");
    }
    function message_types3O(srcs,time){
         $(".chatBox-content-demojia").prepend("<div class=\"clearfloat\">" +
                    "<div class=\"author-name\"><small class=\"chat-date\">"+time+"</small> </div> " +
                    "<div class=\"left\"> <div class=\"chat-avatars\"><img src="+userssImg+" alt=\"头像\" /></div><div class=\"chat-message\"><img src=" + srcs + "></div> " +
                    " </div> </div>");
    }




    function createWebSocket() {
      try {
        ws = new WebSocket(wsUrl);
        init();
      } catch(e) {
        console.log('catch');
        reconnect(wsUrl);
      }
    }
    function init() {
      ws.onclose = function () {
        console.log('链接关闭');
        reconnect(wsUrl);
      };
      ws.onerror = function() {
        console.log('发生异常了');
        reconnect(wsUrl);
      };
      ws.onopen = function (e) {
        var login_data = '{"type":"login","client_name":"kk","token":"'+tokensNew+'"}';
        console.log("websocket握手成功，发送登录数据:"+login_data);
        // $(".CRM_log").css("display","none")
        ws.send(login_data);
        // if(webSend.length > 0 ){
        //     webSend.forEach(function(el,ind){
        //         console.log(el)
        //         ws.send(el)
        //     })
        // }
        console.log(e)
        //心跳检测重置
        heartCheck.start();
      };
    


      ws.onmessage = function (event) {
        //拿到任何消息都说明当前连接是正常的
        // console.log(event);
        console.log(JSON.parse(event.data));
        if(JSON.parse(event.data).type == "login"){
            if(JSON.parse(event.data).code == 200){
                $(".CRM_log").css("display","none")
                if(webSend.length > 0 ){
                    webSend.forEach(function(el,ind){
                        console.log(el)
                        ws.send(el)
                    })
                }
            }else{
                reconnect(wsUrl);
            }
        }
        if(JSON.parse(event.data).client_id){
            speak = JSON.parse(event.data).client_id
        }
        if(JSON.parse(event.data).type == "say"){
            var nei = JSON.parse(event.data).content
            var time = JSON.parse(event.data).time
            var message_type = JSON.parse(event.data).message_type
            if(JSON.parse(event.data).uid == userId){
                messageAjax(userId)
                if(message_type == 1){
                    message_type1O(nei,time)
                }
                if(message_type == 3){
                    message_type3O(nei,time)
                }
            }

           
            $(document).ready(function () {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        }
        if(JSON.parse(event.data).type == "sucess" || JSON.parse(event.data).type == "fail"){
            var timeid = JSON.parse(event.data).timeid
            var myDate = new Date();
            var timeSu = myDate.toLocaleString()
            var dateTmp = timeSu.replace(/\//g,'-') 
            if(webSend.length > 0 ){
                webSend.forEach(function(el2,ind2){
                    console.log(JSON.parse(el2))
                    if(JSON.parse(el2).timeid == timeid){
                        webSend.splice(ind2,1)
                    }
                })
            }

            var newTimeSus
            if(dateTmp.slice(6,7) == "-"){
                // dateTmp.splice(6,1,"0"+dateTmp.slice(5,6))
               newTimeSus = dateTmp.slice(0,5)+"0"+ dateTmp.slice(5)
            }else{
                newTimeSus = dateTmp
            }
            if(newTimeSus.slice(9,10) == " "){
                newTimeSus = newTimeSus.slice(0,8)+"0"+ newTimeSus.slice(8)
            }
            newTimeSus = newTimeSus.slice(0,11) + newTimeSus.slice(13)
            var newTimes = newTimeSus.slice(0,15)

            var info={}
            info.uid = userss.id;
            info.message_type = JSON.parse(event.data).message_type;
            info.head_img = userss.avatar_url;
            info.user_name = userss.nickname;
            info.content = JSON.parse(event.data).content;
            info.time = newTimes;

            // console.log($("#" + timeid))
            $("#" + timeid).html("送达")
            $("#" + timeid).css("color","#03f718")
            var chatss = localStorage.getItem('MESSAGE');
            if(chatss != null){
                var arrs = JSON.parse(chatss)

                var judge = true;
                for(var i = 0; i < arrs.length; i++){
                  if(arrs[i].uid == userss.id){
                    judge = false
                    arrs[i].content = JSON.parse(event.data).content
                    arrs[i].time = newTimes
                    // localStorage.setItem('MESSAGE',JSON.stringify(arrs));
                  }
                }
                // console.log(arrs)
                if(judge){
                  arrs.unshift(info)
                  // localStorage.setItem('MESSAGE',JSON.stringify(arrs));
                }
                arrs.sort(function(a,b){
                    if(a.time>b.time){
                        return -1;
                    }
                    if(a.time<b.time){
                       return 1;
                    }
                    return 0;
                })
                localStorage.setItem('MESSAGE',JSON.stringify(arrs));

                
                // console.log(arrs)
            }else{
                var arrsa = [];
                arrsa.push(info)
                localStorage.setItem('MESSAGE',JSON.stringify(arrsa));
            }
        }
        if(JSON.parse(event.data).type == "read"){
            if(JSON.parse(event.data).id == userId){
                $(".chat-ti").html("已读")
                $(".chat-ti").css("color","#666666")

            }
        }
        // if(JSON.parse(event.data).type == "fail"){
        //     var timeid = JSON.parse(event.data).timeid
        //     $("#" + timeid).html("离线")
        //     $("#" + timeid).css("color","red")
        // }
        // newDiv(event)
        heartCheck.start();
      }
    }

    function reconnect(url) {
      if(lockReconnect) {
        return;
      };

      lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      tt && clearTimeout(tt);
      tt = setTimeout(function () {
        createWebSocket(url);
        lockReconnect = false;
      }, 4000);
    }
    //心跳检测
    var heartCheck = {
      timeout: 30000,
      timeoutObj: null,
      serverTimeoutObj: null,
      start: function(){
        // console.log('start');
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function(){
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          // console.log('心跳');
          ws.send('{"type":"pong"}');
          self.serverTimeoutObj = setTimeout(function() {
            // console.log(111);
            // console.log(ws);
            ws.close();
            // createWebSocket();
          }, self.timeout);

        }, this.timeout)
      }
    }
    createWebSocket(wsUrl);

    //交换手机
    $(".chuantuPhone").click(function(){
        var randoms = parseInt(Math.random() * 10000)
        var timestamp = "a" + (new Date()).getTime() + randoms
        ws.send('{"type":"say","to_client":"'+userId+'","head_img":"' + worker.head_img + '","user_name":"' + worker.name + '","content":"交换手机号","message_type":"5","user_type":"2","timeid":"'+ timestamp +'"}');
        webSend.push('{"type":"say","to_client":"'+userId+'","head_img":"' + worker.head_img + '","user_name":"' + worker.name + '","content":"交换手机号","message_type":"5","user_type":"2","timeid":"'+ timestamp +'"}')
        // message_types5()

        message_types50()
        // ws.send('{"type":"say","to_client":"'+userId+'","content":"' + srcs+'","message_type":"5","user_type":"2"}');
        // alert("已发送")
        $(".chatBox-content").css("margin-top","0")
        $(".div-textarea").css("bottom","0.5rem")
        $(".div-button").css("bottom","0.5rem")
        $(".chuantu").css("display","none")
        chuabpan = true;
        $(document).ready(function () {
            $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
        });
    })

// {"type":"say","to_client":"' + wx.getStorageSync("usersPeoper").id + '","content":"' + inputVal+'","message_type":"1"}
    screenFuc();
    function screenFuc() {
        var topHeight = $(".chatBox-head").innerHeight();//聊天头部高度
        //屏幕小于768px时候,布局change
        var winWidth = $(window).innerWidth();
        // if (winWidth <= 768) {
            var totalHeight = $(window).height(); //页面整体高度
            $(".chatBox-info").css("height", totalHeight - topHeight);
            var infoHeight = $(".chatBox-info").innerHeight();//聊天头部以下高度
            //中间内容高度
            $(".chatBox-content").css("height", infoHeight - 92);
            $(".chatBox-content-demo").css("height", infoHeight - 92);

            $(".chatBox-list").css("height", totalHeight - topHeight);
            $(".chatBox-kuang").css("height", totalHeight - topHeight);
            $(".div-textarea").css("width", winWidth - 106);
        // } else {
        //     $(".chatBox-info").css("height", 495);
        //     $(".chatBox-content").css("height", 448);
        //     $(".chatBox-content-demo").css("height", 448);
        //     $(".chatBox-list").css("height", 495);
        //     $(".chatBox-kuang").css("height", 495);
        //     $(".div-textarea").css("width", 260);
        // }
    }
    (window.onresize = function () {
        screenFuc();
    })();
    //未读信息数量为空时
    var totalNum = $(".chat-message-num").html();
    if (totalNum == "") {
        $(".chat-message-num").css("padding", 0);
    }
    $(".message-num").each(function () {
        var wdNum = $(this).html();
        if (wdNum == "") {
            $(this).css("padding", 0);
        }
    });


    //打开/关闭聊天框
    $(".chatBtn").click(function () {
        $(".chatBox").toggle(10);
    })
    $(".chat-close").click(function () {
        $(".chatBox").toggle(10);
    })
    //进聊天页面
    // $(".chat-list-people").each(function () {
    //     $(this).click(function () {
            var n = $(this).index();
            $(".chatBox-head-one").toggle();
            $(".chatBox-head-two").toggle();
            $(".chatBox-list").fadeToggle();
            $(".chatBox-kuang").fadeToggle();

            //传名字
            $(".ChatInfoName").text("实验");

            //传头像
            $(".ChatInfoHead>img").attr("src", "__ROOT__ /AI_radar/image/my/lytbdx.png");
             // chatAjax(userId,pages,userssImg);
            //聊天框默认最底部
            // $(document).ready(function () {
            //     console.log($("#chatBox-content-demo")[0].scrollHeight)
            //     $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            // });
    //     })
    // });

    //返回列表
    $(".chat-return").click(function () {
        $(".chatBox-head-one").toggle(1);
        $(".chatBox-head-two").toggle(1);
        $(".chatBox-list").fadeToggle(1);
        $(".chatBox-kuang").fadeToggle(1);
    });

    //      发送信息
    $(".fasong").click(function () {
        // var textContent = $(".div-textarea").html().replace(/[\n\r]/g," ")
        // var textContent = $(".div-textarea").html()

        var textContent = $(".div-textarea").html().replace(/[\n\r]/g, '<br>')

        console.log(textContent)

        if (textContent != "") {
            var randoms = parseInt(Math.random() * 10000)
            var timestamp = "a" + (new Date()).getTime() + randoms
            // ws.send('{"type":"say","to_client":"'+userId+'","head_img":"' + worker.head_img + '","user_name":"' + worker.name + '","content":"交换手机号","message_type":"5","user_type":"2"}');
            ws.send('{"type":"say","to_client":"'+userId+'","head_img":"' + worker.head_img + '","user_name":"' + worker.name + '","content":"' + textContent+'","message_type":"1","user_type":"2","timeid":"'+ timestamp +'"}');
            console.log(userId,worker.head_img,worker.name,textContent,timestamp)
            webSend.push('{"type":"say","to_client":"'+userId+'","head_img":"' + worker.head_img + '","user_name":"' + worker.name + '","content":"' + textContent+'","message_type":"1","user_type":"2","timeid":"'+ timestamp +'"}')
            message_type1(textContent,timestamp)
            // $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            //     "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
            //     "<div class=\"right\"> <div class=\"chat-message\"> " + textContent + " </div> " +
            //     "<div class=\"chat-avatars\"><img src=\"__ROOT__ /AI_radar/image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
            //发送后清空输入框
            $(".div-textarea").html("");
            // $(".spans").css("display","inline-block")
            // $(".fasong").css("display","none")
            //聊天框默认最底部
            $(document).ready(function () {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        }
    });

    //      发送表情
    // $("#chat-biaoqing").click(function () {
    //     $(".biaoqing-photo").toggle();
    // });
    $(document).click(function () {
        $(".biaoqing-photo").css("display", "none");
    });
    $("#chat-biaoqing").click(function (event) {
        event.stopPropagation();//阻止事件
    });

    $(".emoji-picker-image").each(function () {
        $(this).click(function () {
            var bq = $(this).parent().html();
            console.log(bq)
            $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
                "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
                "<div class=\"right\"> <div class=\"chat-message\"> " + bq + " </div> " +
                "<div class=\"chat-avatars\"><img src=\"__ROOT__ /AI_radar/image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
            //发送后关闭表情框
            $(".biaoqing-photo").toggle();
            //聊天框默认最底部
            $(document).ready(function () {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        })
    });
    

    // //      发送图片
    // function selectImg(pic) {
    //     if (!pic.files || !pic.files[0]) {
    //         return;
    //     }
    //     var reader = new FileReader();
    //     reader.onload = function (evt) {
    //         var images = evt.target.result;
    //         $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
    //             "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
    //             "<div class=\"right\"> <div class=\"chat-message\"><img src=" + images + "></div> " +
    //             "<div class=\"chat-avatars\"><img src=\"__ROOT__ /AI_radar/image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
    //         //聊天框默认最底部
    //         $(document).ready(function () {
    //             $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
    //         });
    //     };
    //     reader.readAsDataURL(pic.files[0]);

    // }



    //图片上传
    $.ajax({
        url: "https://minitest.17jxyx.com/api/v1/token/file/goods",
        datagoods:"json",
        beforeSend: function(request) {
            request.setRequestHeader("token",window.tokens.token_boss);
        },
        success: function(res){
          console.log(res)
          var tokens = res.token;
          var domain = res.url;
          var config = {
            useCdnDomain: true,
            disableStatisticsReport: true,
            retryCount: 6,
            region: qiniu.region.z2
          };
          var putExtra = {
            fname: "",
            params: {},
            mimeType: null
          };
          function nam(){
            console.log(this)
          }
          uploadWithSDK(tokens, putExtra, config, domain,'goods');
        }
    })
    function uploadWithSDK(token, putExtra, config, domain, typename) {
        // 切换tab后进行一些css操作

        $(".select2").unbind("change").bind("change",function(){
          var types = this.getAttribute("sid")
          var file = this.files[0]
          var finishedAttr = [];
          var compareChunks = [];
          var observable;
          var timestamp;
          if (file) {
            var url = URL.createObjectURL(file);
            var randoms = parseInt(Math.random() * 10000)
            timestamp = "a" + (new Date()).getTime() + randoms
            console.log(url)
            message_type3(url,timestamp)
            //聊天框默认最底部
                $(document).ready(function () {
                    $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                });
            $(".rights").css("color","#333333")
            $(".chatBox-content").css("margin-top","0")
            $(".div-textarea").css("bottom","0.5rem")
        $(".div-button").css("bottom","0.5rem")
            $(".chuantu").css("display","none")


                // document.querySelector(".accountImgs").src = url
            var key = file.name;
            var fr = new FileReader();
            fr.readAsDataURL(file);
              // 添加上传dom面板
              // var board = addUploadBoard(file, config, key,'base64', types, "");
              // if (!board) {
              //   return;
              // }
        // $("#uploading").click(function(){
                putExtra.params["x:name"] = "goods"
                // board.start = true;
              // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
                var error = function(err) {

                  console.log(err);
                  $(".rights").html("发送失败")
                  $(".rights").css("color","red")
                };
                var complete = function(res) {

                  console.log(res)
                  var srcs = "http://resource.17jxyx.com/"+res.key
                  // var randoms = parseInt(Math.random() * 10000)
                  // var timestamp = "a" + (new Date()).getTime() + randoms
                  ws.send('{"type":"say","to_client":"'+userId+'","head_img":"' + worker.head_img + '","user_name":"' + worker.name + '","content":"' + srcs+'","message_type":"3","user_type":"2","timeid":"'+ timestamp +'"}');
                  webSend.push('{"type":"say","to_client":"'+userId+'","head_img":"' + worker.head_img + '","user_name":"' + worker.name + '","content":"' + srcs+'","message_type":"3","user_type":"2","timeid":"'+ timestamp +'"}')
                  $(".rights").remove()
                  // $(".rights").css("display","none")

                   // message_type3(srcs)
                  // $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
                  //   "<div class=\"author-name\"><small class=\"chat-date\"></small> </div> " +
                  //   "<div class=\"right\"> <div class=\"chat-message\"><img src=" + srcs + "></div> " +
                  //   "<div class=\"chat-avatars\"><img src=\"__ROOT__ /AI_radar/image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
               
                  // console.log("http://resource.17jxyx.com/"+res.key)



                };

                var next = function(response) {
                  var chunks = response.chunks||[];
                  var total = response.total;
                  // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
                  for (var i = 0; i < chunks.length; i++) {
                    if (chunks[i].percent === 0 || finishedAttr[i]){
                      continue;
                    }
                    if (compareChunks[i].percent === chunks[i].percent){
                      continue;
                    }
                    if (chunks[i].percent === 100){
                      finishedAttr[i] = true;
                    }
                  }
                  compareChunks = chunks;
                };

                var subObject = { 
                  next: next,
                  error: error,
                  complete: complete
                };
                var subscription;
                var names = file.name
                var rank1 = names.indexOf('.');
                var rank3 = rank1;
                var rank = names.slice(rank3);
                var ranks = token.slice(10,25);
                var timetamp = Date.parse(new Date()) 
                var key = typename+"/"+timetamp+ranks+rank
                console.log(timetamp)
                console.log(key)

             // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(file, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);

            }
        })
    }
// bqxtb01.png

</script>

</body>
</html>
